package com.balabala.gym_system.service.impl;

import com.balabala.api.VenuesFeignClient;
import com.balabala.dto.VenuesDto;
import com.balabala.gym_system.constant.CoachConstant;
import com.balabala.gym_system.constant.KafkaConstant;
import com.balabala.gym_system.mapper.AdminMapper;
import com.balabala.gym_system.mapper.CoachMapper;
import com.balabala.gym_system.mapper.CoachVenueMapper;
import com.balabala.gym_system.pojo.dto.CoachQueryDto;
import com.balabala.gym_system.pojo.dto.CoachDto;
import com.balabala.gym_system.pojo.dto.CoachUpdateByIdsDto;
import com.balabala.gym_system.pojo.dto.CoachUpdateDto;
import com.balabala.gym_system.pojo.entity.Admin;
import com.balabala.gym_system.pojo.entity.Coach;
import com.balabala.gym_system.pojo.entity.CoachVenue;
import com.balabala.gym_system.pojo.vo.CoachQueryVo;
import com.balabala.gym_system.pojo.vo.CoachVo;
import com.balabala.gym_system.service.CoachService;
import com.balabala.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Author:zl
 * Date:2023/5/2 13:55
 */
@Service
@Slf4j
public class CoachServiceImpl extends ServiceImpl<CoachMapper, Coach> implements CoachService {

    @Autowired
    private CoachVenueMapper coachVenueMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private VenuesFeignClient venuesFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 条件模糊查询
     *
     * @param coachQueryDto
     * @return
     */
    @Override
    public List<CoachQueryVo> findCoachById(CoachQueryDto coachQueryDto) {

        PageHelper.startPage(coachQueryDto.getPage(), coachQueryDto.getLimit());
        List<Coach> coaches = list();
        return coaches.stream().map(coach -> {
            CoachQueryVo coachQueryVo = new CoachQueryVo();
            Admin admin = adminMapper.selectById(coach.getAdminId());
            coachQueryVo.setId(coach.getId());
            coachQueryVo.setName(admin.getName());
            coachQueryVo.setSex(admin.getSex());
            coachQueryVo.setPhone(admin.getPhone());
            List<CoachVenue> coachVenues = coachVenueMapper.selectList(new LambdaQueryWrapper<CoachVenue>().eq(CoachVenue::getCoachId, coach.getId()));
            StringBuilder venName = new StringBuilder();
            coachVenues.forEach(coachVenue -> {
                //todo 根据场馆id场馆
                System.out.println("场馆id" + coachVenue.getVenueId());
                Result<VenuesDto> venuesById = venuesFeignClient.getVenuesById(coachVenue.getVenueId());
                String vName = venuesById.getData().getName();
                System.out.println("name" + vName);
                venName.append(vName).append(",");
            });
            coachQueryVo.setVname(venName.toString());
            coachQueryVo.setStatus(admin.getStatus());
            return coachQueryVo;
        }).collect(Collectors.toList());
    }

    /**
     * 添加教练
     *
     * @param coachDto
     * @return
     */
    @Override
    @Transactional
    public Result addCoach(CoachDto coachDto) {
        Coach coach = new Coach();
        BeanUtils.copyProperties(coachDto, coach);
        int insert = getBaseMapper().insert(coach);
        //先查询出刚刚添加的叫教练id
        QueryWrapper<Coach> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_id", coachDto.getAdminId());
        List<Coach> coaches = getBaseMapper().selectList(queryWrapper);

        //添加教练对应的场馆
        CoachUpdateByIdsDto coachUpdateByIdsDto = new CoachUpdateByIdsDto();
        //可能查出多条最后一条数据
        Long id = coaches.get(coaches.size() - 1).getId();
        System.out.println(id);
        coachUpdateByIdsDto.setCoachId(id);
        coachUpdateByIdsDto.setVenueIds(coachDto.getVenueIds());
        this.coachUpdateByIds(coachUpdateByIdsDto);


        if (insert > 0) {
           return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 修改教练信息
     *
     * @param coachDto
     * @return
     */
    @Override
    @Transactional
    public Boolean updateById(CoachUpdateDto coachDto) {
        Coach coach = new Coach();

        //修改教练对应的场馆
        this.updateVenue(coachDto);

        BeanUtils.copyProperties(coachDto, coach);
        int i = getBaseMapper().updateById(coach);
        if (i > 0) {
            kafkaTemplate.send(KafkaConstant.COURSE_CARD_CLEAR,coach.getId()+"").addCallback(success->log.info("消息发送成功：{}",success),fail-> log.info("发送消息失败",fail.getMessage()));

            return true;
        }
        return false;
    }

    /**
     * 修改教练所属场馆
     *
     * @param coachUpdateByIdsDto
     * @return
     */
    @Override
    public void coachUpdateByIds(CoachUpdateByIdsDto coachUpdateByIdsDto) {
        LambdaQueryWrapper<CoachVenue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoachVenue::getCoachId, coachUpdateByIdsDto.getCoachId());
        coachVenueMapper.delete(queryWrapper);
        List<Long> list = coachUpdateByIdsDto.getVenueIds();
        if (!StringUtils.isEmpty(list)) {
            log.debug("循环添加教练所属场馆");
            CoachVenue coachVenue = new CoachVenue();
            //循环添加
            for (int i = 0; i < list.size(); i++) {
                coachVenue.setCoachId(coachUpdateByIdsDto.getCoachId());
                coachVenue.setVenueId(list.get(i));
                coachVenueMapper.insert(coachVenue);
            }
        }
    }

    /**
     * 教练id查询信息
     *
     * @param id
     * @return
     */
    @Override
    public CoachVo findById(Long id) {
        Object o = redisTemplate.boundValueOps(CoachConstant.COACH_CACHE + id).get();
        if(o==null){
            this.findAllName();
        }
        CoachVo coachVo = new CoachVo();
        BeanUtils.copyProperties(o, coachVo);
        return coachVo;
    }

    /**
     * 查询所有教练详情
     *
     * @return
     */
    @Override
    public List<CoachVo> findAllName() {
        List<CoachVo> allName = getBaseMapper().findAllName();
        for (CoachVo co : allName) {
            redisTemplate.boundValueOps(CoachConstant.COACH_CACHE + co.getId()).set(co);
            redisTemplate.boundValueOps(CoachConstant.COACH_CACHE + co.getId()).expire(CoachConstant.COACH_TIME, TimeUnit.SECONDS);
        }
        return allName;
    }

    /**
     * 修改教练场馆信息
     *
     * @param coachUpdateDto
     */
    public void updateVenue(CoachUpdateDto coachUpdateDto) {
        CoachUpdateByIdsDto coachUpdateByIdsDto = new CoachUpdateByIdsDto();
        coachUpdateByIdsDto.setCoachId(coachUpdateDto.getId());
        coachUpdateByIdsDto.setVenueIds(coachUpdateDto.getVenueIds());
        this.coachUpdateByIds(coachUpdateByIdsDto);
    }

}
